<?php

namespace platform;

use app\datacenter\model\Shop;
use think\facade\Log;

/**
 * 美葩平台管理
 */
class MeiPaPlatform
{
    //申请获得的appid
    public string $appid = '3b01eb7ecd0f996d';
    //申请获得的appKey
    public string $appkey = 'a44d19418269709c78550d5c970330b3';
    //请求二维码获取接口
    public string $post_url = 'http://hz.web.meipa.net/api/qrcode/getqrcode';

    /**
     * 查询接口
     * @param array $user
     * @param string $thirdopenid
     * @param string $mac_id
     * @return array
     */
    public function queryInterface(array $user, string $thirdopenid,string $mac_id): array
    {
        //获取当前设备所在位置Code
        $RegionCode = $this->getRegionCode($mac_id);
        //请求参数
        $sex = $user['sex']==0?rand(1,2):$user['sex'];
        $post_data = [
            'time' => time(),
            'apiid' => $this->appid,
            'meipaopenid' => $thirdopenid,
            'apiversion' => 'v2.1',
            'carry_data' => '',
            'openid' => $user['uuid'],
            'nickname' => $user['nickname'],
            'headimgurl' => $user['avatar'],
            'sex' => $sex,
            'country' => '',
            'province' => '',
            'city' => '',
            'provincecode' => $RegionCode['provinceCode'],
            'citycode' => $RegionCode['cityCode'],
            'areacode' => $RegionCode['districtCode'],
            'scene' => '',
        ];

        //安全签名规则
        $signature = $this->sign($post_data['time'], $post_data['openid'], $post_data['carry_data']);
        $params_ready = [
            'json' => array_merge($post_data, ['sing' => $signature])
        ];
        Log::write($post_data);
        $result = httpPost($this->post_url, $params_ready);
        $content = json_decode($result['content'], true);
        Log::write($content);
        //判断结果
        if (isset($content['status']) and $content['status'] == 1) {
            return $content['data'];
        }
        return [];
    }

    /**
     * 构建签名字符
     * @param int|string $time
     * @param string $openid
     * @param string $carry_data
     * @return string
     */
    public function sign(int|string $time, string $openid, string $carry_data): string
    {
        $str = $time . $this->appid . $this->appkey . $openid . $this->appkey . $carry_data;
        return md5($str);
    }

    /**
     * 通过设备ID获取所在地区编码
     * @param string $mac_id
     * @return array
     */
    private function getRegionCode(string $mac_id): array
    {
        $data['provinceCode'] = '0';
        $data['cityCode'] = '0';
        $data['districtCode'] = '0';
        //获取当前设备的shop信息
        $ShopInfo = Shop::getShopInfo($mac_id);
        if ($ShopInfo) {
            $data['provinceCode'] = $ShopInfo['province_id'];
            $data['cityCode'] = $ShopInfo['city_id'];
            $data['districtCode'] = $ShopInfo['region_id'];
        }
        return $data;
    }


}